package myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/***
 * 解密服务器选择
 * <p>
 *@author zhangshuai
 *@date 2021-05-10-10-00
 *@Version 1.0
 */
public class DecodeServerChooseRule extends AbstractLoadBalancerRule {



    public DecodeServerChooseRule() {
    }


    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        System.out.println("lb:"+lb);
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while (server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();

                System.out.println("allList:" + lb.getAllServers());
                System.out.println("upList:" + lb.getReachableServers());

                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                server = upList.get(0);

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    @Override
    public Server choose(Object key) {
        System.out.println("key"+key);
        return this.choose(this.getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
